package reaction

import (
	"context"
	"strconv"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/internal/utils/errorhandler"
	"mall/service/forum/rpc/types/forum"

	"github.com/zeromicro/go-zero/core/logx"
)

type LogReactionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLogReactionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogReactionLogic {
	return &LogReactionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LogReactionLogic) LogReaction(in *forum.LogReactionReq) (*forum.BaseIDResp, error) {
	if in.AuthorId == nil && in.TopicId == nil && in.PostId == nil && in.CommentId == nil {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_CONTENT_ID_INVALID)
	}

	if in.UserId == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_USER_ID_INVALID, "")
	}

	if len(in.Type) == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_TYPE_INVALID, "")
	}

	var topicId uint64
	if in.TopicId != nil && *in.TopicId > 0 {
		topicId = *in.TopicId
	}
	var postId uint64
	if in.PostId != nil && *in.PostId > 0 {
		postId = *in.PostId
	}

	var count uint64
	var log *model.ForumReactionLog
	subFilterMap := make(map[string]map[string][]any)
	subFilterMap[model.ForumReactionLogColumns.UserID] = map[string][]any{
		"equalTo": {in.UserId},
	}
	subFilterMap[model.ForumReactionLogColumns.TopicID] = map[string][]any{
		"equalTo": {topicId},
	}
	subFilterMap[model.ForumReactionLogColumns.PostID] = map[string][]any{
		"equalTo": {postId},
	}
	subFilterMap[model.ForumReactionLogColumns.Type] = map[string][]any{
		"equalTo": {in.Type},
	}
	userLogs, _, err := l.svcCtx.Reaction.GetLogs(l.ctx, model.M{
		"pageSize": uint64(1),
		"orderBy":  model.ForumReactionLogColumns.ID + " DESC",
	}, -1, subFilterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(userLogs) > 0 {
		log = userLogs[0]
		if uint8(in.Status) == log.Status { // 状态未变，即接口被重复调用
			return &forum.BaseIDResp{
				Id: log.ID,
			}, nil
		}
	} else if int32(in.Status) == globalkey.StatusDisabled { // 原来无记录，首次操作即取消，忽略
		return &forum.BaseIDResp{}, nil
	}

	filterMap := make(map[string]map[string][]any)
	subFilterMap[model.ForumReactionLogColumns.TopicID] = map[string][]any{
		"equalTo": {topicId},
	}
	subFilterMap[model.ForumReactionLogColumns.PostID] = map[string][]any{
		"equalTo": {postId},
	}
	filterMap[model.ForumReactionLogColumns.Type] = map[string][]any{
		"equalTo": {in.Type},
	}
	logs, _, err := l.svcCtx.Reaction.GetLogs(l.ctx, model.M{
		"pageSize": uint64(1),
		"orderBy":  model.ForumReactionLogColumns.ID + " DESC",
	}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(logs) > 0 {
		count = logs[0].Count
	}

	now := time.Now()
	date := now.Format("20060102")
	var createDate int
	if i, err := strconv.ParseInt(date, 10, 64); err == nil {
		createDate = int(i)
	}
	newLog := &model.ForumReactionLog{
		TopicID:    topicId,
		PostID:     postId,
		UserID:     in.UserId,
		Type:       in.Type,
		Status:     uint8(in.Status),
		CreatedAt:  now,
		CreateDate: createDate,
	}

	if int32(in.Status) == globalkey.StatusEnabled { // 操作
		count += 1
	} else if count > 0 && int32(in.Status) == globalkey.StatusDisabled { // 取消操作
		count -= 1
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, resultx.StatusError(resultx.DB_ERROR, "")
	}

	newLog.Count = count
	err = l.svcCtx.Reaction.InsertLog(l.ctx, tx, newLog)
	if err != nil {
		tx.Rollback()
		return nil, err
	}

	tx.Commit()

	return &forum.BaseIDResp{
		Id: newLog.ID,
	}, nil
}
